//Server文件夹为测试github三方登录的koa后台测试项目


const clientID = '3c60fe1a26c0500a9e54'
const clientSecret = 'b2fe4300514cdadbd76885896500747dde2602ee'

const Koa = require('koa');
const path = require('path');
const route = require('koa-route');
const axios = require('axios');
var cors = require('koa2-cors');
const { Server } = require('http');

const app = new Koa();

app.use(cors());


const login = async ctx=>{
  if(ctx.query.path) redirectPath=ctx.query.path
    var dataStr=(new Date()).valueOf();
    //重定向到认证接口,并配置参数
    var path="https://github.com/login/oauth/authorize";
    path+='?client_id='+clientID;
    //将地址及参数返回前端
    ctx.body=path;
}

const oauth = async ctx => {
  const requestToken = ctx.request.query.code;
  console.log('authorization code:', requestToken);

  const tokenResponse = await axios({
    method: 'post',
    url: 'https://github.com/login/oauth/access_token?' +
      `client_id=${clientID}&` +
      `client_secret=${clientSecret}&` +
      `code=${requestToken}`,
    headers: {
      accept: 'application/json'
    }
  });

  const accessToken = tokenResponse.data.access_token;
  console.log(`access token: ${accessToken}`);

  const result = await axios({
    method: 'get',
    url: `https://api.github.com/user`,
    headers: {
      accept: 'application/json',
      Authorization: `token ${accessToken}`
    }
  });

  ctx.body=result.data;
  // ctx.cookies.set('user',result.data.login)  //用户名称
  // ctx.cookies.set('icon',result.data.avatar_url)  //用户图片
};

app.use(route.get('/github/login', login));
app.use(route.get('/github/callback', oauth));

app.listen(8080);
